package ran.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ran.constants.Constants;
import ran.domain.es.QuestionES;
import ran.domain.question.dto.QuestionAddDTO;
import ran.domain.question.dto.QuestionEditDTO;
import ran.domain.question.dto.QuestionQueryDTO;
import ran.domain.question.entity.Question;
import ran.domain.question.vo.QuestionDetailVO;
import ran.domain.question.vo.QuestionVO;
import ran.elsticsearch.QuestionRepository;
import ran.enums.ResultCode;
import ran.exception.ServiceException;
import ran.manager.QuestionRedisCacheManager;
import ran.mapper.question.QuestionMapper;
import ran.service.question.IQuestionService;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-10-17
 * Time: 13:45
 */
@Service
@Slf4j
public class QuestionServiceImpl implements IQuestionService {
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionRedisCacheManager questionRedisCacheManager;

    @Override
    public List<QuestionVO> list(QuestionQueryDTO questionQueryDTO) {
        // ExcludeStr不为空, 说明是在竞赛列表中展示的, 并且已经有勾选添加
        if (StrUtil.isNotEmpty(questionQueryDTO.getExcludeStr())) {
            String[] split = questionQueryDTO.getExcludeStr().split(Constants.SPLIT_SEM);
            Set<Long> excludeSet = Arrays.stream(split).map(Long::valueOf).collect(Collectors.toSet());
            questionQueryDTO.setExcludeSet(excludeSet);
        }
        PageHelper.startPage(questionQueryDTO.getPageNum(),questionQueryDTO.getPageSize());// 引入分页插件,可以自动在查询条件下加入分页SQL语句
        return questionMapper.selectQuestionList(questionQueryDTO);
    }
    @Override
    public boolean add(QuestionAddDTO questionAddDTO) {
        List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<Question>().eq(Question::getTitle, questionAddDTO.getTitle()));
        if (!CollectionUtil.isEmpty(questions)) {
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionAddDTO,question);
        log.info("添加的题目是:{}",question);
        int insert = questionMapper.insert(question);
        if (insert <= 0) {
            return false;
        }
        // 存储到ES
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(question, questionES);
        questionRepository.save(questionES);
        // 存储到Redis题目id
        questionRedisCacheManager.addCache(question.getQuestionId());

        return true;
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        Question question = isExist(questionId);
        log.info("获取题目详情:{}",question);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        BeanUtils.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        isExist(questionEditDTO.getQuestionId());
        log.info("修改题目的id:{}",questionEditDTO.getQuestionId());

        Question newQuestion = new Question();
        newQuestion.setQuestionId(questionEditDTO.getQuestionId());
        newQuestion.setTitle(questionEditDTO.getTitle());
        newQuestion.setDifficulty(questionEditDTO.getDifficulty());
        newQuestion.setTimeLimit(questionEditDTO.getTimeLimit());
        newQuestion.setSpaceLimit(questionEditDTO.getSpaceLimit());
        newQuestion.setContent(questionEditDTO.getContent());
        newQuestion.setQuestionCase(questionEditDTO.getQuestionCase());
        newQuestion.setDefaultCode(questionEditDTO.getDefaultCode());
        newQuestion.setMainFuc(questionEditDTO.getMainFuc());

        // 存储到ES
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(newQuestion, questionES);
        questionRepository.save(questionES);

        return questionMapper.updateById(newQuestion);
    }

    @Override
    public int delete(Long questionId) {
        isExist(questionId);
        log.info("删除题目的id:{}",questionId);
        // 从ES中删除
        questionRepository.deleteById(questionId);
        // 从Redis删除题目id
        questionRedisCacheManager.deleteCache(questionId);

        return questionMapper.deleteById(questionId);
    }

    private Question isExist(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        return question;
    }


}
